package cn.wonderland.org.service.impl;

import cn.wonderland.basic.enm.ShopStateEnum;
import cn.wonderland.basic.util.*;
import cn.wonderland.basic.vo.EchartsMidVo;
import cn.wonderland.basic.vo.EchartsVo;
import cn.wonderland.org.domain.Employee;
import cn.wonderland.org.domain.Shop;
import cn.wonderland.org.domain.ShopAuditLog;
import cn.wonderland.org.dto.AdminDto;
import cn.wonderland.org.dto.ShopAuditDto;
import cn.wonderland.org.dto.ShopDto;
import cn.wonderland.org.mapper.EmployeeMapper;
import cn.wonderland.org.mapper.ShopAuditLogMapper;
import cn.wonderland.org.mapper.ShopMapper;
import cn.wonderland.org.service.IShopService;
import cn.wonderland.basic.service.impl.BaseServiceImpl;
import cn.wonderland.org.vo.ShopVo;
import cn.wonderland.system.domain.Role;
import cn.wonderland.system.mapper.RoleMapper;
import cn.wonderland.user.domain.Logininfo;
import cn.wonderland.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wonderland
 * @since 2023-04-27
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper logMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void settlement(ShopDto dto) {
        // 校验
        AdminDto admin = verify(dto);
        // 保存
        save(dto, admin);

    }

    /**
     * 审核通过
     *
     * @param dto
     */
    @Override
    public void auditPass(ShopAuditDto dto) {
        // 非空校验 注解完成
        // 修改shop的状态为审核通过
        Shop shop = new Shop();
        shop.setId(dto.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        // 保存审核日志信息
        ShopAuditLog log = new ShopAuditLog();
        log.setShopId(dto.getShopId());
        // todo 先写死
        log.setAuditId(LoginContext.getLogininfo().getId());
        log.setNote(dto.getNote());
        log.setAuditTime(new Date());
        log.setState(shop.getState());
        logMapper.add(log);
        // 发送短信通知审核通过
        MailUtils.sendMail("1562017408@qq.com",
                "<h1>尊敬的客户，恭喜您提交的店铺申请已经审核通过，请点击下方链接激活您的店铺！：</h1>" +
                        "http://localhost:8080/shop/activity/" + dto.getShopId(), "宠物之家审核通知邮件");

    }

    /**
     * 审核驳回
     *
     * @param dto
     */
    @Override
    public void auditReject(ShopAuditDto dto) {
        // 非空校验 注解完成
        // 修改shop的状态为审核驳回
        Shop shop = new Shop();
        shop.setId(dto.getShopId());
        shop.setState(2);
        this.update(shop);
        // 保存审核日志信息
        ShopAuditLog log = new ShopAuditLog();
        log.setShopId(dto.getShopId());
        // todo 先写死
        log.setAuditId(LoginContext.getLogininfo().getId());
        log.setNote(dto.getNote());
        log.setAuditTime(new Date());
        log.setState(shop.getState());
        logMapper.add(log);
        // 发送短信通知审核通过
        MailUtils.sendMail("1562017408@qq.com",
                "<h1>尊敬的客户，很抱歉您的店铺申请没有通过审核，请点击下方链接重新填写您的信息！：</h1>" +
                        "http://localhost:8081/#/registerAgain?shopId=" + dto.getShopId(), "宠物之家审核通知邮件");
    }

    /**
     * 再次入驻
     *
     * @param
     */
    @Override
    public void settlementAgain(ShopVo shopVo) {
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopVo, shop);
        shop.setState(0);
        shopMapper.update(shop);

    }

    /**
     * 激活店铺
     *
     * @param id
     */
    @Override
    public void activity(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(3);
        this.update(shop);
    }

    @Override
    public void batchSave(List<Shop> shops) {
        shopMapper.batchSave(shops);
    }



    private AdminDto verify(ShopDto dto) {

        AdminDto admin = dto.getAdmin();
        // 1.非空校验 使用注解完成
        // 2.两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())) {
            throw new BussinessException("两次密码不一致！");
        }
        // 3.百度ai审核
        // 3.1文字审核
        if (!BaiduAuditUtils.TextCensor(dto.getName())) {
            throw new BussinessException("店铺名称不合规！");
        }
        // 3.2图片审核
//        if (!BaiduAuditUtils.ImgCensor(dto.getLogo())) {
//            throw new BussinessException("店铺Logo不合规！");
//        }

        // 4.店铺是否入驻过，根据店铺名称对比数据库
        Shop shop = shopMapper.findByName(dto.getName());
        if (shop != null) {
            throw new BussinessException("店铺已注册过，请直接登录！");
        }
        // 5.根据用户名判断当前员工是否是该店铺的员工
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (employee != null && employee.getShopId() != null) {
            // 当前员工是店铺员工
            Shop byId = shopMapper.findById(employee.getShopId());
            // 6.判断当前店铺员工是否已经管理其他店铺
            if (byId.getAdminId().equals(employee.getId())) {
                throw new BussinessException("员工已管理店铺，请更换！");
            }
        }
        return admin;
    }

    private void save(ShopDto dto, AdminDto admin) {
        // 7.验证通过保存数据到数据库 先存店铺信息到shop表中
        Shop dtoShop = dto.getShop();
        this.add(dtoShop);
        // 8.保存管理员信息到emp表中
        Employee emp = new Employee();
        emp.setUsername(admin.getUsername());
        emp.setPhone(admin.getPhone());
        emp.setEmail(admin.getEmail());
        // 获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码加密
        String pwd = MD5Utils.encrypByMd5(salt + admin.getPassword());
        emp.setSalt(salt);
        emp.setPassword(pwd);
        emp.setState(1);
        emp.setShopId(dtoShop.getId());

        // 同步logininfo表信息 2023-5-6 15:29
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(emp, logininfo);
        logininfo.setType(0);
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);
        // 更新emp表的logininfoId 2023-5-6 15:29
        emp.setLogininfoId(logininfo.getId());
        employeeMapper.add(emp);

        // 默认给当前人添加店长角色 如果确定店长的id可以直接写死 2023-5-13 23:04
        List<Role> roleList = roleMapper.findAll();
        Optional<Role> any = roleList.stream().filter(role -> "dz001".equals(role.getSn())).findAny();
        any.ifPresent(role->{
            roleMapper.addMiddle(emp.getId(), Collections.singletonList(role.getId()));
        });

        // 9.修改店铺中adminId为当前管理员emp的id
        Shop shop1 = new Shop();
        shop1.setId(emp.getShopId());
        shop1.setAdminId(emp.getId());
        shopMapper.update(shop1);
    }
}
